package models

import (
	"errors"

	"github.com/github-user/TokTik/helper"
	"gopkg.in/mgo.v2/bson"
)

type User struct {
	ID       bson.ObjectId `bson:"_id"`      // 用户IDs
	VioletID bson.ObjectId `bson:"vid"`      // VioletID
	Token    string        `bson:"token"`    // Violet 访问令牌
	Email    string        `bson:"email"`    // 用户唯一邮箱
	Password string        `bson:"password"` // 密码
	Info     UserInfo      `bson:"info"`     // 用户个性信息
	Star     []Video       `bson:"star"`     // 收藏的视频
	Group    []string      `bson:"group"`    //用户加入的群聊
}

// UserInfo 用户个性信息
type UserInfo struct {
	Name   string `bson:"name"`   // 昵称
	Avatar string `bson:"avatar"` // 头像URL
	Bio    string `bson:"bio"`    // 个人简介
	Gender int    `bson:"gender"` // 性别
}

type FriendInfo struct {
	Email  string `bson:"email"`  // 用户唯一邮箱
	Name   string `bson:"name"`   // 昵称
	Avatar string `bson:"avatar"` // 头像URL
	Bio    string `bson:"bio"`    // 个人简介
	Gender int    `bson:"gender"` // 性别
}

type RegisterReq struct {
	Name     string `json:"name"`
	Email    string `json:"email"`
	Password string `json:"password"`
}

// RegisterReq POST /login login请求
type LoginReq struct {
	Name     string `json:"name"`
	Password string `json:"password"`
}

type ChangeNameReq struct {
	Name string `json:"name"`
}

type ByID struct {
	ID string `json:"_id"`
}

type JwtToken struct {
	Token string `json:"token"`
}

const (
	db         = "TokTik"
	collection = "user"
)

func Register(name, email, password string) error {
	var users []User
	FindAll(db, collection, bson.M{"email": email}, nil, &users)
	if len(users) != 0 {
		return errors.New("email has exits")
	}

	return AddUser(email, password, UserInfo{
		Name:   name,
		Avatar: "",
		Bio:    "",
		Gender: 0,
	})
}

func AddUser(email, password string, userinfo UserInfo) error {
	newUser := bson.NewObjectId()
	var data []byte = []byte(password)
	hashCode := helper.GetSHA256HashCode(data)
	user := User{
		ID:       newUser,
		VioletID: newUser,
		Token:    "",
		Email:    email,
		Password: hashCode,
		Info:     userinfo,
	}
	Insert(db, collection, user)
	return nil
}

func Login(name, password string) error {
	var users []User
	FindAll(db, collection, bson.M{"email": name}, nil, &users)
	if len(users) == 0 {
		return errors.New("user not exits")
	}
	var data []byte = []byte(password)
	hashCode := helper.GetSHA256HashCode(data)
	if hashCode != users[0].Password {
		return errors.New("password error")
	}
	return nil
}
